package com.cincc.cinccimdemo.viewholder;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.cincc.cinccimdemo.BuildConfig;
import com.cincc.cinccimdemo.R;
import com.cincc.cinccimdemo.adapter.ConversationAdapter;
import com.cincc.cinccimdemo.common.Constants;
import com.cincc.cinccimdemo.common.DisplayUtils;
import com.cincc.cinccimdemo.common.FileUtils;
import com.cincc.cinccimdemo.common.MyUtils;
import com.cincc.cinccimdemo.common.TimeUtils;
import com.cincc.cinccimdemo.model.MessageInfoUI;
import com.cincc.cinccimdemo.model.OperationEntity;
import com.cincc.cinccimdemo.ui.conversation.mm.PreviewActivity;
import com.cincc.cinccimdemo.viewmodel.ConversationViewModel;
import com.cincc.im.core.IMSipPhoneCtrl;
import com.cincc.im.model.enums.ImSendType;
import com.cincc.im.model.enums.MessageType;
import com.cincc.im.model.message.ImFileMessage;

import java.io.File;
import java.util.Map;

public class MessageContentHolder extends RecyclerView.ViewHolder {

    private static final String TAG = "MessageContentHolder";
    protected ConversationAdapter adapter;
    TextView tv_time;
    RelativeLayout relativeLayout;
    Context context;
    ConversationViewModel conversationViewModel;
    ImageView faceImage;

    public MessageContentHolder(Context context, View itemView, ConversationAdapter adapter) {
        super(itemView);
        this.context = context;
        this.tv_time = itemView.findViewById(R.id.tv_time);
        this.relativeLayout = itemView.findViewById(R.id.rl_message);
        this.faceImage = itemView.findViewById(R.id.iv_face);
        this.adapter = adapter;
        conversationViewModel = adapter.getConversationViewModel();
    }


    public void bindView(MessageInfoUI uiMessage, int position) {
        setConversationTime(uiMessage, position);
        if (isNormalMsg(uiMessage)) {
            relativeLayout.setOnLongClickListener(v -> {
                longClick(uiMessage);
                return true;
            });
            Glide.with(context).load(uiMessage.getMessageInfo().senderPortrait).placeholder(R.mipmap.avatar_def)
                    .transforms(new CenterCrop(), new RoundedCorners(15))
                    .into(faceImage);
        }
    }

    private void longClick(MessageInfoUI uiMessage) {
        Map<String, Integer> list = MyUtils.getOperations(uiMessage);
        if (!list.isEmpty()) {
            String[] items = list.keySet().toArray(new String[]{});
            //添加列表
            AlertDialog alertDialog3 = new AlertDialog.Builder(context)
                    .setItems(items, (dialogInterface, i) -> {
                        OperationEntity operationEntity = new OperationEntity(list.get(items[i]), uiMessage);
                        conversationViewModel.operationLiveData().postValue(operationEntity);
                    })
                    .create();
            alertDialog3.show();
        }
    }

    protected void preview(MessageInfoUI uiMessage) {
        PreviewActivity.previewMedia(itemView.getContext(), adapter.getMessages(), uiMessage);
    }

    protected void showFile(MessageInfoUI uiMessage) {
        ImFileMessage imMessage = (ImFileMessage) uiMessage.getMessageInfo().imMessage;
        String videoUrl = imMessage.msgContent;
        if (TextUtils.isEmpty(uiMessage.getMessageInfo().localPath)) {
            IMSipPhoneCtrl.getInstance().downloadImFile(uiMessage.getRemoteMsgId(),
                    uiMessage.getMessageInfo().messageType.value(), ImSendType.isP2P(uiMessage.getMessageInfo().imSendType) ? uiMessage.getMessageInfo().senderId : uiMessage.getMessageInfo().groupId,
                    uiMessage.getMessageInfo().imSendType, videoUrl, imResponse -> {
                        if (imResponse.getCode() == 0) {
                            String path = (String) imResponse.getData();
                            imMessage.msgContent = path;
                            openFile(path);
                        }
                    });
        } else {
            openFile(uiMessage.getMessageInfo().localPath);
        }
    }

    private void openFile(String filePath) {
        File file = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //判断版本是否在7.0以上
            uri = FileProvider.getUriForFile(context,
                    context.getPackageName() + ".provider",
                    file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(file);
        }
        //系统会检查当前所有已创建的Task中是否有该要启动的Activity的Task;
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // 若有，则在该Task上创建Activity；若没有则新建具有该Activity属性的Task，并在该新建的Task上创建Activity。
        String type = FileUtils.getMimeTypeFromFile(file);
        intent.setDataAndType(uri, type);
        context.startActivity(intent);
    }

    /**
     * 根据音频时长计算出音频框的宽度
     *
     * @param duration 录音时间
     * @param layout   框框
     */
    public static void setAudioWidth(int duration, RelativeLayout layout, Context context) {
        ConstraintLayout.LayoutParams linearParams = (ConstraintLayout.LayoutParams) layout.getLayoutParams();
        if (duration > Constants.TOTAL_TIME)
            duration = Constants.TOTAL_TIME;
        int increment = DisplayUtils.getScreenWidth(context) / 3 / Constants.TOTAL_TIME * duration;
        linearParams.width = DisplayUtils.dip2px(context, 65) + increment;
        layout.setLayoutParams(linearParams);
    }

    protected void setAudioDrawable(MessageInfoUI message, ImageView ivAudio, boolean isSend) {
        AnimationDrawable animation;
        if (message.isPlaying()) {
            animation = (AnimationDrawable) ivAudio.getBackground();
            if (!animation.isRunning()) {
                animation.start();
            }
        } else {
            ivAudio.setBackground(null);
            if (isSend) {
                ivAudio.setBackgroundResource(R.drawable.audio_animation_send_list);
            } else {
                ivAudio.setBackgroundResource(R.drawable.audio_animation_receive_list);
            }
        }
    }

    /**
     * 设置会话页面时间显示，DEFAULT_INTERVAL_TIME以内的消息不显示时间
     *
     * @param uiMessage
     * @param position
     */
    private void setConversationTime(MessageInfoUI uiMessage, int position) {
        long messageTime = Long.parseLong(uiMessage.getMessageInfo().messageTime) / 1000;
        if (position == 0) {
            tv_time.setText(TimeUtils.getMsgFormatTime(uiMessage.getMessageInfo().messageTime));
            tv_time.setVisibility(View.VISIBLE);
        } else {
            MessageInfoUI previousItem = adapter.getItem(position - 1);
            long preMsgTime = Long.parseLong(previousItem.getMessageInfo().messageTime) / 1000;
            if (messageTime - preMsgTime > Constants.DEFAULT_INTERVAL_TIME) {
                tv_time.setVisibility(View.VISIBLE);
                tv_time.setText(TimeUtils.getMsgFormatTime(uiMessage.getMessageInfo().messageTime));
            } else {
                tv_time.setVisibility(View.GONE);
            }
        }
    }

    // 判断是否是文本，图片，语言，视频，文件，定位，卡片等普通消息
    private boolean isNormalMsg(MessageInfoUI messageInfoUI) {
        return messageInfoUI.getMessageInfo().messageType == MessageType.TEXT ||
                messageInfoUI.getMessageInfo().messageType == MessageType.IMAGE ||
                messageInfoUI.getMessageInfo().messageType == MessageType.VOICE ||
                messageInfoUI.getMessageInfo().messageType == MessageType.VIDEO ||
                messageInfoUI.getMessageInfo().messageType == MessageType.FILE ||
                messageInfoUI.getMessageInfo().messageType == MessageType.CARD ||
                messageInfoUI.getMessageInfo().messageType == MessageType.FORWARD ||
                messageInfoUI.getMessageInfo().messageType == MessageType.SEQUENCE ||
                messageInfoUI.getMessageInfo().messageType == MessageType.CUSTOM;
    }
}
